<?php

class Application_Plugin_Acl extends Zend_Controller_Plugin_Abstract{

  private $_controller = array(
    'controller' => 'error',
    'action' => 'denied'
  );

  public function __construct()
  {
    $acl = new Zend_Acl();

    //roles
    $acl->addRole(new Zend_Acl_Role('public'));
    $acl->addRole(new Zend_Acl_Role('user'), 'public');
    $acl->addRole(new Zend_Acl_Role('core'));

    //resources
    $acl->add(new Zend_Acl_Resource('users'));


    //permissions
    $acl->deny();
    $acl->allow('core', null);

    //Guest rights
    $acl->allow('public', null);

    //User rights

    Zend_Registry::set('acl', $acl);
  }


  public function preDispatch(Zend_Controller_Request_Abstract $request) {
    $auth = Zend_Auth::getInstance();
    $acl = Zend_Registry::get('acl');

    if($auth->hasIdentity()) {
      $role = 'core';//new Application_Model_Roles();
      //$role = $roles->getRole(Zend_Auth::getInstance()->getIdentity()->user_role_id);
    }
    else {
      $role = 'public';
    }

    if (!$acl->hasRole($role)) {
      $role = 'public';
    }

    $controller = $request->controller;
    $action = $request->action;

    if (!$acl->has($controller)) {
      $controller = null;
    }
    if ($role == 'public') {
      if ($request->getActionName() != 'registration') {
//        $request->setModuleName('user');
//        $request->setControllerName('Auth');
//        $request->setActionName('login');
      }
    } elseif (!$acl->isAllowed($role, $controller, $action)){
      $request->setControllerName($this->_controller['controller']);
      $request->setActionName($this->_controller['action']);
    }
  }
}

